<template>
	<!-- 修改表单 -->
	<el-form
		label-width="90"
		ref="editFormRef"
		:model="editForm"
		:rules="editRules"
	>
		<el-form-item
			label="分类名称"
			prop="name"
		>
			<el-input
				v-model="editForm.name"
				placeholder="请输入分类名称"
			></el-input>
		</el-form-item>
		<el-form-item
			label="分类选项"
			prop="isSecond"
		>
			<el-radio-group
				v-model="editForm.isSecond"
				:disabled="currentType === CATEGORY_OPS_TYPE.modify && !isSecond"
			>
				<el-radio :value="false">一级分类</el-radio>
				<el-radio :value="true">二级分类</el-radio>
			</el-radio-group>
		</el-form-item>
		<el-form-item
			v-show="editForm.isSecond"
			label="上级分类"
		>
			<el-select
				v-model="editForm.pid"
				placeholder="请选择内容"
				prop="pid"
			>
				<el-option
					v-for="item in baseNode"
					:key="item.id"
					:label="item.name"
					:value="item.id"
				/>
			</el-select>
		</el-form-item>
		<el-form-item
			label="文件提交"
			v-show="editForm.isSecond"
			prop=""
		>
			<el-upload
				class="upload-demo"
				ref="uploadRef"
				drag
				action="http://127.0.0.1:8360/admin/upload/picture"
				multiple
				:headers="{ jwt: token }"
				:data="{ 'Content-Type': 'multipart/formdata', type: 'category_picture' }"
				:on-success="onFileSubmit"
			>
				<el-icon class="el-icon--upload"><upload-filled /></el-icon>
				<div class="el-upload__text">Drop file here or <em>click to upload</em></div>
				<template #tip>
					<div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
				</template>
			</el-upload>
		</el-form-item>
		<el-form-item>
			<el-button
				v-show="currentType === CATEGORY_OPS_TYPE.modify"
				type="primary"
				@click="submitCategory"
				>修 改</el-button
			>
			<el-button
				v-show="currentType === CATEGORY_OPS_TYPE.add"
				type="primary"
				@click="submitCategory"
				>添加</el-button
			>
			<el-button @click="resetForm">重 置</el-button>
		</el-form-item>
	</el-form>
</template>

<script setup>
	import { UploadFilled } from '@element-plus/icons-vue'
	import { addCategoryApi, getCategoryApi, getCategoryByIdApi, saveCategoryApi } from '@/api/category'
	import { ElMessage, ElMessageBox } from 'element-plus'
	import { reactive, ref } from 'vue'
	import { defineProps, defineEmits } from 'vue'
	// 导入操作类型
	import { CATEGORY_OPS_TYPE, CATEGORY_MAP } from '@/constant/category'
	import { useUserStore } from '@/store/user'
	const { token } = useUserStore()

	const { currentType, id } = defineProps({
		// 表单id (如有 比如修改情况下)
		id: {
			type: Number,
		},
		// 执行操作（当前的操作状态）
		currentType: {
			type: String,
			required: true,
		},
	})
	// 是否是二级标签 默认的标签
	let isSecond
	let curData
	const emits = defineEmits()
	// 控制对话框的显示与隐藏
	const editFormRef = ref(null)

	// 表单
	const editForm = reactive({
		id: '',
		name: '',
		picture: '',
		pid: '',
	})

	// 修改规则
	const editRules = {
		name: [
			{ required: true, message: '标题不能为空', trigger: 'blur' },
			{ min: 2, max: 10, message: '长度要在2-10之间', trigger: 'blur' },
		],
		pid: [{ required: true, message: '父标题不能为空', trigger: 'blur' }],
	}

	// 表单重置
	const resetForm = async () => {
		try {
			await ElMessageBox.confirm('确认重置吗', '重置', {
				confirmButtonText: '确认',
				type: 'warning',
				cancelButtonText: '取消',
			})
			editFormRef.value.resetFields()
			for (let key in editForm) {
				editForm[key] = curData[key]
			}
		} catch (e) {}
	}

	// upload DOM
	const uploadRef = ref(null)

	// 文件上传
	const onFileSubmit = (result) => {
		if (result.errno === 1000) {
			// 上传失败
			return ElMessage.warning(result.errmsg)
		}
		const {
			data: { savepath },
		} = result
		editForm.picture = savepath
	}

	// 表单提交
	function submitCategory() {
		editFormRef.value.validate(async (valid) => {
			// 校验
			if (!valid) return ElMessage.error('表单格式错误')
			try {
				let ret
				if (currentType === CATEGORY_OPS_TYPE.modify) {
					// 修改
					// 如果是修改为一级分类 那么 pid = 0
					if (!editForm.isSecond) editForm.pid = 0
					ret = await saveCategoryApi(editForm)
				} else if (currentType === CATEGORY_OPS_TYPE.add) {
					// 添加
					// 上传文件
					uploadRef.value.submit()
					// 将表单提交到数据库中
					ret = await addCategoryApi(editForm)
				}
				// 关闭对话框 重新加载内容(可选择优化)
				emits('onFisish', '提交')
			} catch (e) {}
		})
	}

	// 根节点数据
	const baseNode = ref([])
	// 根节点加载
	const loadCategory = async () => {
		const data = await getCategoryApi()
		baseNode.value = data.data.filter((v) => v.pid === 0)
	}

	// 设置当前行的数据（如果有）
	const getCategoryRow = async () => {
		if (currentType === CATEGORY_OPS_TYPE.modify) {
			// 当前状态是修改
			const { data } = await getCategoryByIdApi(id)
			// 赋值上去
			for (let key in editForm) {
				editForm[key] = data[key]
			}
			editForm.isSecond = isSecond = data.pid !== 0
		}

		if (currentType === CATEGORY_OPS_TYPE.add) {
			editForm.isSecond = true
		}
		curData = { ...editForm }
	}
	// 加载根节点
	loadCategory()
	// 加载表单数据（回显）
	getCategoryRow()

	// 给父组件调用
	defineExpose({
		resetForm,
	})
</script>

<style scoped lang="scss">
	.el-form {
		margin-left: 40px;
	}
</style>
